package com.example.base_kotlin_xml.view

import androidx.fragment.app.viewModels
import com.blankj.utilcode.util.LogUtils
import com.example.base_kotlin_xml.R
import com.example.base_kotlin_xml.databinding.FragmentDatastoreBinding
import com.example.base_kotlin_xml.model.DatastoreViewModel
import com.example.base_model.bean.general.UserInfo
import com.example.base_model.ext.castTo
import com.example.base_model.ext.castToListOf
import com.example.base_model.ext.castToMap
import com.example.base_model.ext.whenStatus
import com.example.base_model.network.load.LoadingStrategy
import com.example.base_model.network.request_param.RequestParamInterface
import com.example.base_model.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map

/**
 * @Author: jiangKunKun
 * @CreateDate: 2025/8/6
 * @Description: datastore数据存储(SP)
 * @SpittingGrooves
 */
@AndroidEntryPoint
class DatastoreFragment : BaseFragment<FragmentDatastoreBinding>() {

    val vModel: DatastoreViewModel by viewModels()
    override fun initObservers() {
        launchAndCollect {
            vModel.uiState
                .map { it.isLoading(LoadingStrategy.MAIN) } // 使用枚举检查状态
                .distinctUntilChanged()
                .collectLatest { isLoading ->
                    if (isLoading) {
                        showLoading("加载中...")
                    } else {
                        LogUtils.d("isLoading 关闭")
                        hideLoading()
                    }
                }
        }
        launchAndCollect {
            vModel.uiState.map { it.saveResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room添加 开始状态")
                        },
                        dataSuccess = {
                            roonParamCallBack(it.requestParam)
                            LogUtils.d("room添加 成功状态", it.requestParam)
                        },
                        error = {
                            LogUtils.d("room添加 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room添加 结束状态")
                        }
                    )
                }
        }
        launchAndCollect {
            vModel.userInfoFlow.collect {
                LogUtils.d("实时监听", it.toString())
                it.let { it ->
                    mBinding.mtvDatastoreUserInfo.text = it.toString()
                }
            }
        }
        launchAndCollect {
            vModel.uiState.map { it.userInfoResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("获取用户信息开始", it.toString())
                        },
                        dataSuccess = {
                            LogUtils.d("获取用户信息成功", it.data.toString())
                            mBinding.mtvDatastoreUserInfo.text = it.data.toString()
                        },
                        error = {
                            LogUtils.d("获取用户信息失败", it.toString())
                        },
                        finish = {
                            LogUtils.d("获取用户信息完成", it.toString())
                        }
                    )
                }
        }
        launchAndCollect {
            vModel.uiState.map { it.clearResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("删除开始", it.toString())
                        },
                        dataSuccess = {
                            LogUtils.d("删除成功", it.toString())
                        },
                        error = {
                            LogUtils.d("删除失败", it.toString())
                        },
                        finish = {
                            LogUtils.d("删除完成", it.toString())
                        }
                    )
                }
        }
    }

    override fun initClickEvents() {
        mBinding.btnDatastore1.setOnClickListener {
            // 保存数据
            vModel.saveUserInfo(
                UserInfo(
                    name = "张三",
                    age = 18,
                    email = "zhangsan@163.com",
                    phone = "12345678901",
                    id = 101,
                    isVip = true
                )
            )
        }
        mBinding.btnDatastore2.setOnClickListener {
            // 存储单个用户基础字段Name
            vModel.saveUserInfo(   UserInfo(
                name = "艾泽拉斯",
                age = 18,
                email = "zhangsan@163.com",
                phone = "12345678901",
                id = 101,
                isVip = true
            ))
        }
        mBinding.btnDatastore3.setOnClickListener {
            // 存储单个用户基础字段Age
            vModel.saveUserInfo(   UserInfo(
                name = "艾泽拉斯",
                age = 30,
                email = "zhangsan@163.com",
                phone = "12345678901",
                id = 101,
                isVip = true
            ))
        }
        mBinding.btnDatastore4.setOnClickListener {
            // 获取用户信息
            vModel.loadUserInfo()
        }
        mBinding.btnDatastore5.setOnClickListener {
            // 删除用户信息
            vModel.clearDeviceInfo()
        }
    }
    private fun roonParamCallBack(param: RequestParamInterface?) {
        if (param is RequestParamInterface) {
            // 处理 List<Bean>
            param.castToListOf<UserInfo> { list ->
                list.forEach { it ->
                    LogUtils.d("castToListOf 成功: ${it.toString()}")
                }
            }

            // 处理 Map
            param.castToMap { map ->
                LogUtils.d("原始 Map 参数: $map")
            }

            // 处理单个 Bean
            param.castTo<UserInfo> { bean ->
                LogUtils.d("castTo 成功: $bean")
            }
        }
    }

    override fun initData() {

    }

    override fun attachLayoutRes(): Int = R.layout.fragment_datastore
}